package com.shqcjd.preinstallglass.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.shqcjd.preinstallglass.R;
import com.shqcjd.preinstallglass.api.ApiService;
import com.shqcjd.preinstallglass.app.MyApp;
import com.shqcjd.preinstallglass.helper.rxjavahelper.RxObserver;
import com.shqcjd.preinstallglass.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.preinstallglass.model.ResponseData;
import com.shqcjd.preinstallglass.model.eventbus.FinishVideotape;
import com.shqcjd.preinstallglass.model.eventbus.RestartVideotapeEvent;
import com.shqcjd.preinstallglass.model.pojo.EquipmentGroupBean;
import com.shqcjd.preinstallglass.model.pojo.IntentEquipmentBean;
import com.shqcjd.preinstallglass.model.pojo.ViewChildBean;
import com.shqcjd.preinstallglass.ui.activity.remote.ExpertTypeActivity;
import com.shqcjd.preinstallglass.ui.base.BaseActivity;
import com.shqcjd.preinstallglass.ui.base.BasePresenter;
import com.shqcjd.preinstallglass.util.Config;
import com.shqcjd.preinstallglass.util.ToastUtils;
import com.shqcjd.preinstallglass.util.UIUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class EquipmentGroupsActivity extends BaseActivity {

    @BindView(R.id.iv_item_bg)
    ImageView ivItemBg;
    @BindView(R.id.tv_item_equipment_group_name)
    TextView tvItemEquipmentGroupName;
    @BindView(R.id.cb_item_equipment_group_switch)
    CheckBox cbItemEquipmentGroupSwitch;
    @BindView(R.id.rb_item_equipment_group_true)
    RadioButton rbItemEquipmentGroupTrue;
    @BindView(R.id.rb_item_equipment_group_false)
    RadioButton rbItemEquipmentGroupFalse;
    @BindView(R.id.rb_item_equipment_group)
    RadioGroup rbItemEquipmentGroup;
    @BindView(R.id.rl_bg)
    RelativeLayout rlBg;
    @BindView(R.id.ll_euipment_item)
    LinearLayout llEuipmentItem;
    @BindView(R.id.btn_finish)
    Button btnFinish;
    @BindView(R.id.sv_equipment)
    ScrollView svEquipment;
    @BindView(R.id.ll_euipment)
    LinearLayout llEuipment;
    @BindView(R.id.btn_guide)
    Button btnGuide;

    private Context context;
    private int tId, epId;
    private String kks;
    private final int END_CODE = 12312;
    private String nextKks = "";

    public List<RadioGroup> radioGroupList = new ArrayList<>();
    public List<RelativeLayout> relativeLayoutList = new ArrayList<>();
    private ArrayList<CheckBox> checkBoxeList = new ArrayList<>();
    private List<LinearLayout> linearLayoutList = new ArrayList<>();



    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_equipment_group2;
    }

    @Override
    public void init() {
        super.init();
        kks = getIntent().getStringExtra("kks");
        tId = getIntent().getIntExtra("tId", -1);
        epId = getIntent().getIntExtra("epId", -1);
    }

    @Override
    public void initView() {
        super.initView();
        context = this;
        EventBus.getDefault().register(this);//订阅
        btnFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btnGuide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, ExpertTypeActivity.class));
            }
        });
        getData();
    }


    private void initListView(List<EquipmentGroupBean.EquipmentCheckListBean.EquipmentChildrenBeanX> equipment_check_list) {
        for (int i = 0; i < equipment_check_list.size(); i++) {
            int finali = i;
            ViewGroup vChild = (ViewGroup) LayoutInflater.from(context).inflate(R.layout.item_equipment_group_child, null);
            TextView tv_item_equiment_group_name = vChild.findViewById(R.id.tv_item_equiment_group_name);
            CheckBox cb_item_equipment_group_switch = vChild.findViewById(R.id.cb_item_equipment_group_switch);
            RadioButton rb_item_equipment_group_confirm = vChild.findViewById(R.id.rb_item_equipment_group_confirm);
            RadioButton rb_item_equipment_group_cancle = vChild.findViewById(R.id.rb_item_equipment_group_cancle);
            RadioGroup rb_item_equipment_group = vChild.findViewById(R.id.rb_item_equipment_group);
            RelativeLayout rl_bg = vChild.findViewById(R.id.rl_bg);
            LinearLayout ll_item_equipment = vChild.findViewById(R.id.ll_item_equipment);
            linearLayoutList.add(ll_item_equipment);

            tv_item_equiment_group_name.setText(equipment_check_list.get(i).equipment_name);
            cb_item_equipment_group_switch.setChecked(equipment_check_list.get(i).running);
            if (equipment_check_list.get(i).check_normal == 1) {
                rb_item_equipment_group_confirm.setChecked(true);
            } else if (equipment_check_list.get(i).check_normal == 2) {
                rb_item_equipment_group_cancle.setChecked(true);
            }
            cb_item_equipment_group_switch.setTag(new ViewChildBean(i, -1));
            checkBoxeList.add(cb_item_equipment_group_switch);
            cb_item_equipment_group_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    ViewChildBean mBean = (ViewChildBean) buttonView.getTag();
                    for (int i = 0; i < checkBoxeList.size(); i++) {
                        ViewChildBean mChildBean = (ViewChildBean) checkBoxeList.get(i).getTag();
                        if (mBean.id == mChildBean.parentId) {
                            checkBoxeList.get(i).setChecked(isChecked);
                        }
                    }
                }
            });

            cb_item_equipment_group_switch.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openOrCloseSwitchHttp(equipment_check_list.get(finali).kks);
                }
            });

            rb_item_equipment_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    if (checkedId == R.id.rb_item_equipment_group_cancle) {
                        Intent it = new Intent(context, EquipmentAbnormalActivity.class);
                        it.putExtra("eId", equipment_check_list.get(finali).equipment_id);
                        it.putExtra("tId", tId);
                        startActivityForResult(it, END_CODE);
                    } else if (checkedId == R.id.rb_item_equipment_group_confirm) {
                        updateTrue(equipment_check_list.get(finali).equipment_id);
                    }
                    scrollPosition(group);
                    focusItem((Integer) group.getTag());
                }
            });
            rb_item_equipment_group.setTag(radioGroupList.size());
            radioGroupList.add(rb_item_equipment_group);
            relativeLayoutList.add(rl_bg);
            llEuipmentItem.addView(vChild);
            for (int j = 0; j < equipment_check_list.get(i).equipment_children.size(); j++) {
                View vChildItem = LayoutInflater.from(context).inflate(R.layout.item_equipment_group_item, null);
                int finalj = j;
                TextView textView = vChildItem.findViewById(R.id.rl_item_equiment_group_name);
                textView.setText(equipment_check_list.get(i).equipment_children.get(j).equipment_name);
                LinearLayout ll_item_equipment_item = vChildItem.findViewById(R.id.ll_item_equipment);
                linearLayoutList.add(ll_item_equipment_item);
                RadioButton rb_confirm = vChildItem.findViewById(R.id.rb_item_equipment_group_confirm);
                RadioButton rb_cancle = vChildItem.findViewById(R.id.rb_item_equipment_group_cancle);
                RadioGroup rb_item_equipment_group_item = vChildItem.findViewById(R.id.rb_item_equipment_group_item);
                RelativeLayout rl_bg_item = vChildItem.findViewById(R.id.rl_bg);
                rb_item_equipment_group_item.setTag(radioGroupList.size());
                relativeLayoutList.add(rl_bg_item);
                if (equipment_check_list.get(i).equipment_children.get(j).check_normal == 1) {
                    rb_confirm.setChecked(true);
                } else if (equipment_check_list.get(i).equipment_children.get(j).check_normal == 2) {
                    rb_cancle.setChecked(true);
                }

                CheckBox cb_switch = vChildItem.findViewById(R.id.cb_item_equipment_group_switch);
                cb_switch.setChecked(equipment_check_list.get(i).equipment_children.get(j).running);
                cb_switch.setTag(new ViewChildBean(j, i));
                checkBoxeList.add(cb_switch);
                cb_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                    }
                });

                cb_switch.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        openOrCloseSwitchHttp(equipment_check_list.get(finali).equipment_children.get(finalj).kks);
                    }
                });

                rb_item_equipment_group_item.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        if (checkedId == R.id.rb_item_equipment_group_cancle) {
                            Intent it = new Intent(context, EquipmentAbnormalActivity.class);
                            it.putExtra("eId", equipment_check_list.get(finali).equipment_children.get(finalj).equipment_id);
                            it.putExtra("tId", tId);
                            startActivityForResult(it, END_CODE);
                        } else if (checkedId == R.id.rb_item_equipment_group_confirm) {
                            updateTrue(equipment_check_list.get(finali).equipment_children.get(finalj).equipment_id);
                        }
                        focusItem((Integer) group.getTag());
                        scrollPosition(group);
                    }
                });
                radioGroupList.add(rb_item_equipment_group_item);
                vChild.addView(vChildItem);
            }
        }
        focusItem(-1);
    }

    private void getData() {
        ApiService.equipmentGroupHttp(tId, kks)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<EquipmentGroupBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<EquipmentGroupBean> responseData) {
                        if (responseData.retCode != 10000) {
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                            hideWaitingDialog();
                            return;
                        }
                        List<EquipmentGroupBean.EquipmentCheckListBean.EquipmentChildrenBeanX> childs = new ArrayList<>();
                        childs.addAll(responseData.data.equipment_check_list.equipment_children);
                        nextKks = responseData.data.next.kks;

                        linearLayoutList.add(llEuipment);
                        relativeLayoutList.add(rlBg);
                        rbItemEquipmentGroup.setTag(radioGroupList.size());
                        radioGroupList.add(rbItemEquipmentGroup);
                        cbItemEquipmentGroupSwitch.setChecked(responseData.data.equipment_check_list.running);
                        tvItemEquipmentGroupName.setText(responseData.data.equipment_check_list.equipment_name);
                        if (responseData.data.equipment_check_list.check_normal == 1) {
                            rbItemEquipmentGroupTrue.setChecked(true);
                        } else if (responseData.data.equipment_check_list.check_normal == 2) {
                            rbItemEquipmentGroupFalse.setChecked(true);
                        }
                        cbItemEquipmentGroupSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                            @Override
                            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                                for (int i = 0; i < checkBoxeList.size(); i++) {
                                    checkBoxeList.get(i).setChecked(isChecked);
                                }
                            }
                        });
                        cbItemEquipmentGroupSwitch.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                openOrCloseSwitchHttp(responseData.data.equipment_check_list.kks);
                            }
                        });
                        rbItemEquipmentGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                            @Override
                            public void onCheckedChanged(RadioGroup group, int checkedId) {
                                if (checkedId == R.id.rb_item_equipment_group_false) {
                                    Intent it = new Intent(context, EquipmentAbnormalActivity.class);
                                    it.putExtra("eId", responseData.data.equipment_id);
                                    it.putExtra("tId", tId);
                                    startActivityForResult(it, END_CODE);
                                } else if (checkedId == R.id.rb_item_equipment_group_true) {
                                    updateTrue(responseData.data.equipment_id);
                                }
                                scrollPosition(group);
                                focusItem((Integer) group.getTag());
                            }
                        });

                        initListView(childs);
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void scrollPosition(View v) {
        int[] location = new int[2];
        linearLayoutList.get((Integer) v.getTag() + 1 == linearLayoutList.size() ? (Integer) v.getTag() : (Integer) v.getTag() + 1).getLocationOnScreen(location);
        svEquipment.smoothScrollTo(svEquipment.getScrollX(), svEquipment.getScrollY() + location[1]);
    }

    private void srollRvHeight(LinearLayout linearLayout, int he) {
        int[] location = new int[2];
        linearLayout.getLocationOnScreen(location);
        srollRv(location[1], linearLayout.getHeight() + he);
    }

    public void srollRv(int y, int h) {
        svEquipment.smoothScrollBy(svEquipment.getScrollX(), svEquipment.getScrollY() + y + h);
    }


    int oldFocusPos = -1;

    public void focusItem(int i) {
        if (oldFocusPos != -1) {
            relativeLayoutList.get(oldFocusPos).getChildAt(0).setVisibility(View.GONE);
        }
        relativeLayoutList.get(i + 1 == relativeLayoutList.size() ? i : i + 1).getChildAt(0).setVisibility(View.VISIBLE);
        oldFocusPos = i + 1 == relativeLayoutList.size() ? i : i + 1;
    }

    /**
     * 巡检设备组中设备标为正常
     */
    public void updateTrue(int mEid) {
        ApiService.getGroupTrue(tId, mEid)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData responseData) {
                        if (responseData.retCode != 10000) {
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }
                        hideWaitingDialog();
                        nextInspect();
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    public void openOrCloseSwitchHttp(String mKks) {
        ApiService.openOrCloseSwitchHttp(mKks.replace("#", "%23"))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData responseData) {
                        if (responseData.retCode != 10000) {
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    /**
     * 判断所有的radiobutton有没有被选中
     *
     * @return
     */
    public boolean isCheckAll() {
        for (int i = 0; i < radioGroupList.size(); i++) {
            RadioGroup radioGroup = radioGroupList.get(i);
            RadioButton rb1 = (RadioButton) radioGroup.getChildAt(0);
            RadioButton rb2 = (RadioButton) radioGroup.getChildAt(1);
            if (!rb1.isChecked() && !rb2.isChecked()) {
                return false;
            }
        }
        return true;

    }

    private void nextInspect(){
        if (isCheckAll()) {
            if (!nextKks.equals("")) {
                isInspectionData(nextKks);
            } else {
                finish();
                Toast.makeText(context, "所有设备巡检完毕", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void isInspectionData(String kksStr) {
        ApiService.intentEquipmentHttp(kksStr, tId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<IntentEquipmentBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<IntentEquipmentBean> responseData) {
                        if (responseData.retCode == 10000) {
                            if (responseData.data.check_gps) {
                                RxPermissions permissions = new RxPermissions(EquipmentGroupsActivity.this);
                                permissions.setLogging(true);
                                permissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                                        .subscribe(new Consumer<Boolean>() {
                                            @Override
                                            public void accept(Boolean aBoolean) throws Exception {
                                                if (aBoolean) {
                                                    showWaitingDialog("获取当前坐标...");
                                                    MyApp.startLocation();
                                                    MyApp.setOnLocationCallBack(new MyApp.OnLocationInterface() {
                                                        @Override
                                                        public void onLocationInterface(AMapLocation aMapLocation) {
                                                            hideWaitingDialog();
                                                            LatLng desLatLng = UIUtils.getGpsChangeLocation(responseData.data.latitude, responseData.data.longitude, context);
                                                            //当前坐标
                                                            double cLongitude = aMapLocation.getLongitude();
                                                            double cLatitude = aMapLocation.getLatitude();
                                                            float distance = AMapUtils.calculateLineDistance(desLatLng, new LatLng(cLatitude, cLongitude));
                                                            if (distance < Config.INSPECTION_DISTANCE) {
                                                                if (responseData.data.isgroup) {
                                                                    Intent it = new Intent(context, InspectionStandardActivity.class);
                                                                    it.putExtra("kks", kksStr);
                                                                    it.putExtra("tId", tId);
                                                                    startActivity(it);
                                                                } else {
                                                                    Intent it = new Intent(context, NewEquipmentInspectionActivity.class);
                                                                    it.putExtra("tId", tId);
                                                                    it.putExtra("kks", kksStr);
                                                                    startActivity(it);
                                                                }
                                                                finish();
                                                            } else {
                                                                Toast.makeText(context, "当前位置距离巡检点超过了"+Config.INSPECTION_DISTANCE+"米", Toast.LENGTH_SHORT).show();
                                                            }
                                                        }
                                                    });
                                                } else {
                                                    ToastUtils.show(EquipmentGroupsActivity.this, "巡检需要获取定位的权限", Toast.LENGTH_SHORT);
                                                }
                                            }
                                        });
                            } else {
                                if (responseData.data.isgroup) {
                                    Intent it = new Intent(context, InspectionStandardActivity.class);
                                    it.putExtra("kks", kksStr);
                                    it.putExtra("tId", tId);
                                    startActivity(it);
                                } else {
                                    Intent it = new Intent(context, NewEquipmentInspectionActivity.class);
                                    it.putExtra("tId", tId);
                                    it.putExtra("kks", kksStr);
                                    startActivity(it);
                                }
                                finish();
                            }
                        } else {
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                        Toast.makeText(context, "任务不存在", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==END_CODE){
            nextInspect();
        }
    }

    /**
     * 重新开启全程录像
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onRestartVideotapeEvent(RestartVideotapeEvent event) {
        //开启全程录像
//        EventBus.getDefault().post(new CreateVideotape(this,  epId+ "", tId + ""));
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().post(new FinishVideotape(0));
        EventBus.getDefault().unregister(this);//解除订阅
    }
}
